package com.hss.rxjava;



import com.hss.base.interfaces.IHttpCallBack;
import com.hss.rxjava.result.ResultBaseBean;
import com.hss.rxjava.result.ResultObject;

import retrofit2.adapter.rxjava.HttpException;
import retrofit2.adapter.rxjava.Result;
import rx.Subscriber;

/**
 * Created by WuXiaolong
 * on 2016/9/22.
 * github:https://github.com/WuXiaolong/
 * weibo:http://weibo.com/u/2175011601
 * 微信公众号：吴小龙同学
 * 个人博客：http://wuxiaolong.me/
 */
public abstract class ApiCallback<M extends ResultBaseBean> extends Subscriber<M>  implements IHttpCallBack<M>{

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            //httpException.response().errorBody().string()
            int code = httpException.code();
            String msg = httpException.getMessage();
//            LogUtil.d("code=" + code);
            if (code == 504) {
                msg = "网络不给力";
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
            }
            onFailure(msg);
        } else {
            onFailure(e.getMessage());
        }
        onFinish();
    }

    @Override
    public void onNext(M result) {

        if (result !=null ){
            if ( result.status == 1){
                onSuccess(result);
            }else if (result.status == 999){
                onExitLogin();
            }else {
                onDataErr(result.message == null ? "数据异常":result.message);
            }
        }else {
            onDataErr("数据异常");
        }
        onFinish();
    }

    @Override
    public void onCompleted() {
        onFinish();
    }
}
